<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">

      <el-form-item label="筹备组名" prop="nickname">
        <el-input v-model="queryParams.nickname" placeholder="请输入筹备组名字" clearable size="small" @keyup.enter.native="handleQuery" />
      </el-form-item>

      <el-form-item label="电话" prop="mobile">
        <el-input v-model="queryParams.mobile" placeholder="请输入筹备组名字" clearable size="small" @keyup.enter.native="handleQuery" />
      </el-form-item>

      <el-form-item label="小区" prop="community_id">
        <el-select v-model="queryParams.community_id" placeholder="请选择小区">
          <el-option v-for="item in CommunityList" :key="item.id" :label="item.name" :value="item.id">
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd" v-hasPermi="['system:post:add']">新增</el-button>
      </el-col>

      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete" v-hasPermi="['system:post:remove']">删除</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="DataList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />


      <el-table-column label="ID" width="50" align="center" prop="ID">
        <template slot-scope="scope">
          {{scope.row.id}}
        </template>
      </el-table-column>

      <el-table-column label="用户名" width="200" align="center" prop="username">
        <template slot-scope="scope">
          {{scope.row.username}}
        </template>
      </el-table-column>

      <el-table-column label="筹备组名字" width="200" align="center" prop="nickname">
        <template slot-scope="scope">
          {{scope.row.nickname}}
        </template>
      </el-table-column>

      <el-table-column label="电话" width="200" align="center" prop="mobile">
        <template slot-scope="scope">
          {{scope.row.mobile}}
        </template>
      </el-table-column>

      <el-table-column label="管理小区" width="200" align="center" prop="community_name">
        <template slot-scope="scope">
          {{scope.row.community_name}}
        </template>
      </el-table-column>

      <el-table-column label="头像" align="center" prop="avatar" :show-overflow-tooltip="true">
        <template slot-scope="scope">
          <img :src="scope.row.avatar" width="50" />
        </template>
      </el-table-column>

      <el-table-column label="到期时间" width="200" align="center" prop="expire_time" :show-overflow-tooltip="true">
        <template slot-scope="scope">
          {{scope.row.expire_time}}
        </template>
      </el-table-column>







      <el-table-column label="状态" align="center" prop="state" :show-overflow-tooltip="true">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_normal_disable" :value="scope.row.state" />
        </template>
      </el-table-column>



      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)" v-hasPermi="['system:post:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)" v-hasPermi="['system:post:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="queryParams.page" :limit.sync="queryParams.pageSize" @pagination="getList" />

    <!-- 添加开始 -->
    <el-dialog :close-on-click-modal="false" :title="title" :visible.sync="open" append-to-body>
      <el-form ref="form" :model="form" label-width="120px" :rules="rules" style="height: 500px;overflow-y: scroll;">



        <el-form-item label="用户名" prop="username">
          <el-input v-model="form.username" placeholder="请输入用户名" clearable size="small" />
        </el-form-item>




        <el-form-item label="筹备组名字" prop="nickname">
          <el-input v-model="form.nickname" placeholder="请输入筹备组名字" clearable size="small" />
        </el-form-item>

        <el-form-item label="头像" prop="avatar">
          <el-upload :action="upload_url" :headers="headers" :before-upload="handleSetHeaders" :on-success="handleFileSuccess" :show-file-list="false" class="avatar-uploader">
            <img v-if="form.avatar!==undefined" :src="form.avatar" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>

        <el-form-item label="到期时间" prop="expire_time">
          <el-date-picker v-model="form.expire_time" type="date" placeholder="选择日期" format="yyyy 年 MM 月 dd 日" value-format="yyyy-MM-dd">
          </el-date-picker>
        </el-form-item>




        <el-form-item label="电话" prop="mobile">
          <el-input v-model="form.mobile" placeholder="请输入电话" clearable size="small" />
        </el-form-item>


        <el-form-item label="管理小区" prop="community_id">
          <el-select v-model="form.community_id" placeholder="请选小区">
            <el-option v-for="item in CommunityList" :key="item.id" :label="item.name" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>




        <el-form-item label="状态" prop="state">
          <el-radio-group v-model="form.state">
            <el-radio v-for="dict in dict.type.sys_normal_disable" :key="dict.value" :label="dict.value">{{dict.label}}</el-radio>
          </el-radio-group>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 添加结束 -->
    <el-dialog :visible.sync="dialogVisible">
      <img width="100%" :src="dialogImageUrl" alt="">
    </el-dialog>
  </div>
</template>

<script>
  import * as Advert from "@/api/operation/advert";
  import * as Community from "@/api/operation/community";
  import * as Preparatory from "@/api/operation/preparatory";
  import * as AdvertPlace from "@/api/operation/advert_place";
  import * as Auth from '@/utils/auth'

  export default {
    name: "Advert",
    dicts: ['sys_normal_disable'],
    data() {
      return {
        upload_url: process.env.VUE_APP_BASE_URL + "/file/upload",
        headers: Auth.getHeader(),
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        open: false,
        form: {},
        rules: [],
        title: "",
        // 日期范围
        dateRange: [],
        DataList: [],
        CommunityList: [], //小区列表
        // 查询参数
        queryParams: {
          page: 1,
          pageSize: 10
        },

        preparatoryParams: {
          page: 1,
          pageSize: 100
        },
        dialogVisible: false,
        dialogImageUrl: undefined,
        PlaceList: [],
        rewards: [{
            id: 'hp',
            title: "HP",
            number: undefined,
            chance: undefined
          },
          {
            id: 'vit',
            title: "VIT",
            number: undefined,
            chance: undefined
          },
          {
            id: 'happiness',
            title: "Happy",
            number: undefined,
            chance: undefined
          },
          {
            id: 'fight',
            title: "Fight",
            number: undefined,
            chance: undefined
          }
        ],

        // 表单校验
        rules: {
          username: [{
            required: true,
            message: "用户名不能为空",
            trigger: "blur"
          }],
          nickname: [{
            required: true,
            message: "筹备组名字不能为空",
            trigger: "blur"
          }],
          avatar: [{
            required: true,
            message: "头像不能为空",
            trigger: "blur"
          }],
          expire_time: [{
            required: true,
            message: "到期时间不能为空",
            trigger: "blur"
          }],
          mobile: [{
              required: true,
              message: "电话不能为空",
              trigger: "blur"
            },
            {
              pattern: /^(13|14|15|17|18)\d{9}$/,
              message: "请输入有效的手机号码",
              trigger: "blur"
            }
          ],
          community_id: [{
            required: true,
            message: "小区不能为空",
            trigger: "blur"
          }],
          state: [{
            required: true,
            message: "状态不能为空",
            trigger: "blur"
          }],
        },
        Area: [],
        cityQuery: [],
        areaQuery: [],

        province: {},
        city: '',
        area: ""
      };
    },

    watch: {
      // 监听省级
      province: function(newValue) {
        this.cityQuery = [],
          this.areaQuery = [],
          this.city = '',
          this.area = ""
        this.Area.forEach((item) => {
          if (newValue.label === item.label) {
            this.cityQuery = item.children
            console.log('watch-city', this.cityQuery)
            console.log('watch-province', this.province)
            this.$set(this.form, 'province_id', this.province.value);
            this.$set(this.form, 'province_name', this.province.label);
          }
        })
      },
      // 监听市级
      city: function(newValue) {
        this.areaQuery = [],
          this.area = ""
        this.cityQuery.forEach((item) => {
          if (newValue.label === item.label) {
            this.areaQuery = item.children
            console.log('watch-areaQuery', this.areaQuery)
            this.$set(this.form, 'city_id', this.city.value);
            this.$set(this.form, 'city_name', this.city.label);
          }
        })
      },

    },
    created() {
      this.Area = require('../../../utils/area.json');
      this.getList();
      this.getPreparatoryList();

    },
    methods: {
      ysarea() {
        this.$set(this.form, 'district_id', this.area.value);
        this.$set(this.form, 'district_name', this.area.label);
      },
      profuc() {
        console.log(this.queryParams.province.children);
        this.cityQuery = this.queryParams.province.children;
        this.areaQuery = [];
        this.$set(this.queryParams, 'province_id', this.queryParams.province.value);
        this.$set(this.queryParams, 'city', '');
        this.$set(this.queryParams, 'area', '');
      },

      citfuc() {
        console.log(this.queryParams.city);
        this.areaQuery = this.queryParams.city.children;
        this.$set(this.queryParams, 'area', '');
        this.$set(this.queryParams, 'city_id', this.queryParams.city.value);
      },

      arefuc() {
        this.$set(this.queryParams, 'district_id', this.queryParams.area.value);
      },

      /** 查询筹备组列表 */
      getList() {
        this.loading = true;
        Preparatory.List(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
          this.DataList = response.data.rows;
          this.total = response.data.total;
          this.loading = false;
        });
      },

      /** 查询小区列表 */
      getPreparatoryList() {
        this.loading = true;
        Community.List(this.preparatoryParams).then(response => {
          this.CommunityList = response.data.rows;
          this.total = response.data.total;
          this.loading = false;
        });
      },

      // 表单重置
      reset() {
        this.form = {};
        this.resetForm("form");
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.page = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.dateRange = [];
        this.resetForm("queryForm");
        this.queryParams = {
          page: 1,
          pageSize: 10
        };
        this.handleQuery();
      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.id)
        this.single = selection.length != 1
        this.multiple = !selection.length
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.reset();
        this.open = true;
        this.title = "添加筹备组(默认密码:123456)";
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.reset();
        const Id = row.id || this.ids
        Preparatory.Show(Id).then(response => {
          this.form = response.data;
          console.log('handleUpdate-response.data', response.data)
          this.open = true;
          this.title = "修改筹备组(默认密码:123456)";
        });
      },
      /** 提交按钮 */
      submitForm: function() {
        if (this.form.community_id) {
          const selectedCommunity = this.CommunityList.find(item => item.id === this.form.community_id);
          this.$set(this.form, 'community_name', selectedCommunity.name);
        }

        console.log('表单数据', this.form);
        this.$refs["form"].validate(valid => {
          if (valid) {
            if (this.form.id != undefined) {
              Preparatory.Update(this.form).then(response => {
                this.$modal.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              });
            } else {
              Preparatory.Add(this.form).then(response => {
                this.$modal.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              });
            }
          }
        });
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        const Id = row.id || this.ids;
        this.$modal.confirm('是否确认删除编号为"' + Id + '"的数据项？').then(function() {
          return Preparatory.Delete(Id);
        }).then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        }).catch(() => {});
      },
      handleSetHeaders() {
        this.headers = Auth.getHeader();
      },
      /****文件上传*****/
      handleFileSuccess(res) {

        // this.form.avatar = res.data;
        this.$set(this.form, 'avatar', res.data);

      }
    },
  };
</script>
<style>
  .avatar-uploader {
    width: 100px;
  }

  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }

  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }

  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 100px;
    height: 100px;
    line-height: 100px;
    text-align: center;
  }

  .avatar {
    width: 100px;
    height: 100px;
    display: block;
  }
</style>
